<template>
  <div class="followup-list">
    <!-- 页面头部 -->
    <div class="header">
      <h2>跟进记录</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增跟进
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <div class="filter">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="跟进类型">
          <el-select v-model="searchForm.type" placeholder="请选择跟进类型" clearable style="width: 180px">
            <el-option 
              v-for="type in typeOptions" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getFollowupList">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 跟进列表 -->
    <el-table :data="followupList" v-loading="loading" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="customer_name" label="客户名称" width="150" />
      <el-table-column prop="followup_type" label="跟进类型" width="120">
        <template #default="{ row }">
          <el-tag>{{ getTypeLabel(row.followup_type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="跟进内容" min-width="200" show-overflow-tooltip />

      <el-table-column prop="next_followup_time" label="下次跟进时间" width="150" />
      <el-table-column label="创建时间" width="150">
        <template #default="{ row }">
          {{ formatDateTime(row.create_time, 'YYYY-MM-DD HH:mm', '-') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
          <el-dropdown size="small">
            <el-button type="default" size="small">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                <el-dropdown-item @click="handleDelete(row)" style="color: #f56c6c">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 跟进表单抽屉 -->
    <followup-form
      v-model="formVisible"
      :followup-id="currentFollowupId"
      @success="handleFormSuccess"
    />

    <!-- 跟进详情抽屉 -->
    <el-drawer
      v-model="viewDrawerVisible"
      direction="rtl"
      size="80%"
      :class="'followup-detail-drawer'"
    >
      <template #header>
        <div class="drawer-header detail-header">
          <div class="drawer-title">
            <div class="drawer-icon">
              <el-icon><View /></el-icon>
            </div>
            跟进详情
          </div>
          <div class="drawer-close" @click="viewDrawerVisible = false">
            <el-icon><Close /></el-icon>
          </div>
        </div>
      </template>

      <div class="drawer-content" v-if="currentFollowup">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="客户名称">{{ currentFollowup.user_name || `客户${currentFollowup.customer_id}` }}</el-descriptions-item>
            <el-descriptions-item label="跟进类型">
              <el-tag>{{ getTypeLabel(currentFollowup.followup_type) }}</el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="创建时间">{{ formatDateTime(currentFollowup.create_time) }}</el-descriptions-item>
            <el-descriptions-item label="下次跟进时间">{{ currentFollowup.next_followup_time || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 跟进内容 -->
        <div class="detail-section">
          <h3>跟进内容</h3>
          <div class="content-box">{{ currentFollowup.content || '无' }}</div>
        </div>

        <!-- 备注信息 -->
        <div class="detail-section">
          <h3>备注信息</h3>
          <div class="content-box">{{ currentFollowup.content || '无备注' }}</div>
        </div>
      </div>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="viewDrawerVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit(currentFollowup)">编辑</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowDown, View, Close } from '@element-plus/icons-vue'
import { ElDrawer, ElDescriptions, ElDescriptionsItem } from 'element-plus'
import followupApi, { type FollowupTypeOption } from '@/api/crm/followup'
import type { Followup } from '@/types/crm'

// 组件导入
import FollowupForm from './components/FollowupForm.vue'

// 数据定义
const loading = ref(false)
const followupList = ref<Followup[]>([])
const typeOptions = ref<FollowupTypeOption[]>([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  type: '' as string | number | null,
  dateRange: [] as string[]
})

// 分页
const pagination = reactive({
  current: 1,
  limit: 20,
  total: 0
})

// 表单抽屉
const formVisible = ref(false)
const currentFollowupId = ref<number | undefined>(undefined)

// 详情抽屉
const viewDrawerVisible = ref(false)
const currentFollowup = ref<Followup | null>(null)

// 获取跟进类型选项
const getTypeOptions = async () => {
  try {
    const response = await followupApi.getFollowupTypeOptions()
    typeOptions.value = response.data
  } catch (error) {
    console.error('获取跟进类型选项失败:', error)
    // 如果API失败，使用默认选项
    typeOptions.value = [
      { label: '电话联系', value: 1 },
      { label: '微信沟通', value: 2 },
      { label: '邀约到场', value: 3 },
      { label: '上门拜访', value: 4 }
    ]
  }
}

// 获取跟进列表
const getFollowupList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      limit: pagination.limit,
      customerName: searchForm.customerName,
      type: searchForm.type || undefined,
      startDate: searchForm.dateRange[0],
      endDate: searchForm.dateRange[1]
    }
    
    const response = await followupApi.list(params)
    const { list, total } = response.data
    
    followupList.value = list
    pagination.total = total || 0
  } catch (error) {
    console.error('获取跟进列表失败:', error)
    ElMessage.error('获取跟进列表失败')
  } finally {
    loading.value = false
  }
}

// 导入公共的日期时间格式化函数
import { formatDateTime } from '@/utils/format'
const getTypeLabel = (type: string | number) => {
  const option = typeOptions.value.find(opt => opt.value === type)
  return option ? option.label : type
}

// 重置搜索
const resetSearch = () => {
  searchForm.customerName = ''
  searchForm.type = ''
  searchForm.dateRange = []
  pagination.current = 1
  getFollowupList()
}

// 页面大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size
  getFollowupList()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getFollowupList()
}

// 新增跟进
const handleAdd = () => {
  currentFollowupId.value = undefined
  formVisible.value = true
}

// 编辑跟进
const handleEdit = (row: any) => {
  currentFollowupId.value = row.id
  viewDrawerVisible.value = false
  formVisible.value = true
}

// 查看跟进
const handleView = (row: any) => {
  currentFollowup.value = row
  viewDrawerVisible.value = true
}



// 删除跟进
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该跟进记录吗？', '提示', {
      type: 'warning',
    })

    await followupApi.del({ id: row.id })
    ElMessage.success('删除成功')
    getFollowupList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除跟进记录失败:', error)
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false
  getFollowupList()
}

onMounted(() => {
  getFollowupList()
  getTypeOptions()
})
</script>

<style scoped>
.followup-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter {
  background: #f5f7fa;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 跟进详情抽屉样式 */
.followup-detail-drawer {
  --el-drawer-width: 80%;
}

.followup-detail-drawer :deep(.el-drawer__body) {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 自定义抽屉头部样式 */
.drawer-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 蓝色渐变背景 - 详情抽屉 */
.drawer-header.detail-header {
  background: linear-gradient(to right, #409eff, #66b1ff, #8cc5ff);
  color: white;
}

.drawer-title {
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.drawer-title .drawer-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  margin-right: 8px;
  font-size: 16px;
}

/* 关闭按钮样式优化 */
.drawer-close {
  cursor: pointer;
  font-size: 20px;
  color: white;
  transition: all 0.3s ease;
  padding: 5px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.1);
}

.drawer-close:hover {
  background-color: rgba(255, 255, 255, 0.2);
  transform: rotate(90deg);
}

.drawer-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 详情区域样式 */
.detail-section {
  margin-bottom: 30px;
}

.detail-section h3 {
  color: #409eff;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  border-left: 3px solid #409eff;
  padding-left: 12px;
}

.content-box {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  min-height: 80px;
  line-height: 1.6;
  color: #606266;
}

/* 抽屉底部按钮区域 */
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 跟进详情抽屉按钮样式 - 蓝色 */
.followup-detail-drawer .drawer-footer .el-button--primary {
  background: linear-gradient(to right, #409eff, #66b1ff, #8cc5ff);
  border: none;
}

.followup-detail-drawer .drawer-footer .el-button--primary:hover {
  background: linear-gradient(to right, #3690ff, #4096ff, #7cb8ff);
}
</style>